﻿//===================================================================================
// Copyright (c) Ryan Garrett.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================

using Caffeine.Core.Metadata;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Input;

namespace Caffeine.Core
{
    /// <summary>
    /// Provides a base class for creating implementations of ICommand
    /// </summary>
    public abstract class ModelCommandBase : ICommand, INotifyPropertyChanged
    {
        #region State

        private PropertyChangedEventHandler _propertyChanged;
        private EventHandler _canExecuteChanged;
        private Boolean _canExecuteResult;
        private Nullable<Boolean> _canExecuteResultOverride;
        private Nullable<Boolean> _canExecuteResultOverrideForNulls;
        private readonly ModelBase _parent;

        #endregion

        #region Constructors

        internal ModelCommandBase(ModelBase parent)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }

            _parent = parent;
        }

        #endregion

        #region Public

        /// <summary>
        /// Raised whenever this command's ability to execute has been changed
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add
            {
                _canExecuteChanged += value;
            }
            remove
            {
                _canExecuteChanged -= value;
            }
        }

        /// <summary>
        /// Raised whenever an observable property of this command has changed
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged
        {
            add
            {
                _propertyChanged += value;
            }
            remove
            {
                _propertyChanged -= value;
            }
        }
        
        /// <summary>
        /// Gets the parent of this command
        /// </summary>
        public ModelBase Parent
        {
            get
            {
                return _parent;
            }
        }

        /// <summary>
        /// Gets the result returned by the last call to CanExecute. Defaults to false if CanExecute has not been called yet.
        /// </summary>
        public Boolean CanExecuteResult
        {
            get
            {
                return _canExecuteResult;
            }
            private set
            {
                if (_canExecuteResult != value)
                {
                    _canExecuteResult = value;
                    RaisePropertyChanged("CanExecuteResult");
                }
            }
        }

        /// <summary>
        /// Gets or sets a flag that manually controls whether or not this command can execute. This property will
        /// be ignored if it's value is set to null.
        /// </summary>
        public Nullable<Boolean> CanExecuteResultOverride
        {
            get
            {
                return _canExecuteResultOverride;
            }
            set
            {
                if (_canExecuteResultOverride != value)
                {
                    _canExecuteResultOverride = value;
                    RaisePropertyChanged("CanExecuteResultOverride");
                }
            }
        }

        /// <summary>
        /// Gets or sets the value to return when a null parameter is received. This property will
        /// be ignored if it's value is set to null.
        /// </summary>
        public Nullable<Boolean> CanExecuteResultOverrideForNulls
        {
            get
            {
                return _canExecuteResultOverrideForNulls;
            }
            set
            {
                if (_canExecuteResultOverrideForNulls != value)
                {
                    _canExecuteResultOverrideForNulls = value;
                    RaisePropertyChanged("CanExecuteResultOverrideForNulls");
                }
            }
        }

        /// <summary>
        /// Queries whether or not this command can execute.
        /// </summary>
        /// <param name="parameter">Parameter for command to consider</param>
        /// <returns>True if this command can execute, otherwise false</returns>
        public Boolean CanExecute(Object parameter)
        {
            try
            {
                CanExecuteResult = CanExecuteResultOverride ?? OnCanExecute(parameter);
            }
            catch(Exception ex)
            {
                if (Parent.CommandExceptionHandler == null)
                {
                    throw;
                }
                else
                {
                    Parent.CommandExceptionHandler.HandleCanExecuteException(ex);
                }
            }
            
            return CanExecuteResult;
        }

        /// <summary>
        /// Execute this command
        /// </summary>
        /// <param name="parameter">Parameter for command to consider</param>
        public void Execute(Object parameter)
        {
            try
            {
                OnExecute(parameter);
            }
            catch(Exception ex)
            {
                if (Parent.CommandExceptionHandler == null)
                {
                    throw;
                }
                else
                {
                    Parent.CommandExceptionHandler.HandleExecuteException(ex);
                }
            }
        }

        /// <summary>
        /// Raises the CanExecuteChanged event
        /// </summary>
        public void RaiseCanExecuteChanged()
        {
            if (_canExecuteChanged != null)
            {
                _canExecuteChanged(this, EventArgs.Empty);
            }
        }

        /// <summary>
        /// Releases all observers from this command's events
        /// </summary>
        public void ReleaseObservers()
        {
            _canExecuteChanged = null;
            _propertyChanged = null;
        }

        #endregion

        #region Internal

        internal ModelCommandMetadata GetMetadata()
        {
            return new ModelCommandMetadata()
            {
                CanExecuteResult = CanExecuteResult,
                CanExecuteResultOverride = CanExecuteResultOverride,
                CanExecuteResultOverrideForNulls = CanExecuteResultOverrideForNulls
            };
        }

        internal void ApplyMetadata(ModelCommandMetadata metadata)
        {
            _canExecuteResult = metadata.CanExecuteResult;
            _canExecuteResultOverride = metadata.CanExecuteResultOverride;
            _canExecuteResultOverrideForNulls = metadata.CanExecuteResultOverrideForNulls;
        }

        #endregion

        #region Protected

        /// <summary>
        /// Override to implement CanExecute(parameter) logic
        /// </summary>
        /// <param name="parameter">Parameter for command to consider</param>
        /// <returns>True if the command can execute, otherwise false</returns>
        protected abstract Boolean OnCanExecute(Object parameter);

        /// <summary>
        /// Override to implement Execute(parameter) logic
        /// </summary>
        /// <param name="parameter">Parameter for command to consider</param>
        protected abstract void OnExecute(Object parameter);

        #endregion

        #region Private

        private void RaisePropertyChanged(String propertyName)
        {
            if (_propertyChanged != null)
            {
                _propertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion
    }
}
